<template>
  <el-page-header class="page-head" @back="$router.push({path: `/user/${id}`})" title="个人主页">
    <template #content>
      <span style="font-weight: 600;">修改资料</span>
    </template>
  </el-page-header>
  <el-form
  label-position="right"
  label-width="100px"
  style="max-width: 800px">
    <el-form-item label="新密码">
      <el-input type="password" v-model="userPassword" show-password />
      <el-button type="info" @click="updatepwd">修改密码</el-button>
    </el-form-item>
    <el-form-item label="用户名">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="身份">
      <el-select v-model="form.role.id">
        <el-option v-for="role in roles"
        :key="role.id"
        :label="role.name"
        :value="role.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updateUserInfo">修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { post } from '../../utils/common/api'
import { getUser } from '../../utils/user'
import { hashPassword } from '../../utils/user'
  export default {
    data() {
      return {
        id: undefined,

        userPassword: '',

        dialogVisible: false,

        roles: [],

        form: {
          name: '',
          role: {
            id: undefined
          }
        }
      }
    },
    methods: {
      updatepwd() {
        var that = this
        getUser(function(user) {
          post('/user/password', {
            id: user.id,
            password: hashPassword(that.userPassword)
          }).then(function(res) {
          ElNotification({
            title: '修改成功',
            message: '密码修改成功',
            type: 'success',
            position: 'bottom-right',
          })
        })
        })
      },
      updateUserInfo() {
        var that = this
        post('/user/update', { 
          id: that.id,
          mod: that.form
        }).then(function(res) {
          ElNotification({
            title: '修改成功',
            message: '用户信息修改成功',
            type: 'success',
            position: 'bottom-right',
          })
        })
      }
    },
    mounted() {
      var that = this
      post('/user/role/all', {}).then(function(res) {
        that.roles = res.list
      })
      getUser(function(user) {
        that.id = user.id
        that.form.name = user.name
        that.form.role.id = user.role.id
      })
    }
  }
</script>

<style scoped>
.page-head {
  margin-bottom: 40px;
}

.el-button {
  display: inline-block;
  margin-left: 10px;
}

.el-input {
  width: 300px;
}
</style>